<template>
  <div class="position-relative width-100 height-100">
    <div class="position-absolute tab-item-container" :style="{...styles.positionStyles, ...styles.sizeStyles}">
      <div class="tab-container" :style="{...styles.backgroundStyles}">
        <div
          v-for="tab in widget.UI.data.items"
          :key="tab.widgetId" class="flex-item tab-box"
          :style="containerStyle(tab.widgetId)"
          @click="tabChange(tab.widgetId)">
          <i v-if="tab.icon" class="iconfont"
             :class="backgroundIconClass(tab.icon)"
             :style="{'fontSize': widget.UI.data.tabData.iconSize + 'px',}"></i>
          <pre :style="{'fontSize': widget.UI.data.tabData.textSize + 'px'}"> {{tab.text}}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {formatColor} from '@/utils';
  import {mapState} from 'vuex';
  import {WidgetTabBar} from "@/modules/IDE/widget/atom/widgetTabBar";
  import iconfont from '@/assets/font/iconfont.json';
  import {WidgetFactory} from "@/modules/IDE/widgetFactory";

  export default {
    name: 'TabBar',
    props: {
      widget: {
        type: WidgetTabBar,
        default: () => {}
      },
      isSelectMode: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
      };
    },
    computed: {
      ...mapState({
        activeTheme: state => state.ide.activeTheme,
      }),
      state() {
        if (!this.widget || !this.widget.UI.state) return;
        return this.widget.getCurrentState();
      },
      styles() {

        const {tempRect = {}} = this.widget;
        const {tabSize = {}, tabPosition = {}, tabData = {}} = this.widget.UI.data;
        const {
          layout = 'bottom', radius = 0, offset = {top: 0, bottom: 0, left: 0, right: 0},
          backGroundColor = '', activeBackGroundColor = '', color = '', activeColor = ''
        } = tabData;
        const backgroundStyles = {};
        const componentStyles = {};
        const textStyles = {};
        const contentStyles = {};
        const positionStyles = {};
        const sizeStyles = {};

        backGroundColor && (backgroundStyles.backgroundColor = formatColor(backGroundColor, this.activeTheme));
        activeBackGroundColor && (componentStyles.backgroundColor = formatColor(activeBackGroundColor, this.activeTheme));
        color && (textStyles.color = formatColor(color, this.activeTheme));
        activeColor && (contentStyles.color = formatColor(activeColor, this.activeTheme));
        // 根据标签栏布局配置，决定靠顶部还是底部
        switch (layout) {
          case 'bottom':
            positionStyles.bottom = `${offset.bottom}px`;
            tabPosition.top = tempRect.height - offset.bottom - tabSize.height;
            break;
          case 'top':
            positionStyles.top = `${offset.top}px`;
            tabPosition.top = offset.top;
            break;
          default:
            break;
        }
        // 根据 offset 和 tabSize 计算出具体坐标和尺寸
        positionStyles.left = `${offset.left}px`;
        sizeStyles.width = `${tempRect.width - offset.left - offset.right}px`;
        sizeStyles.height = `${tabSize.height}px`;
        tabPosition.left = offset.left;
        tabSize.width = tempRect.width - offset.left - offset.right;
        radius && (positionStyles.borderRadius = radius + 'px');
        return {
          backgroundStyles: backgroundStyles,
          componentStyles: componentStyles,
          textStyles: textStyles,
          contentStyles: contentStyles,
          sizeStyles: sizeStyles,
          positionStyles: positionStyles
        };

      },
      containerStyle() {
        return (widgetId) => {
          const {tabData = {}} = this.widget.UI.data;
					const widget = WidgetFactory.getWidgetById(widgetId);
	        const isActive = !this.isSelectMode ? widget.display : widget.displayForPicker;
          const {color, activeColor, backGroundColor: bgColor, activeBackGroundColor: activeBgColor} = tabData;
          return {
            'color': formatColor(isActive ? activeColor : color, this.activeTheme),
            'backgroundColor': formatColor(isActive ? activeBgColor : bgColor, this.activeTheme)
          }
        };
      },
	    backgroundIconClass() {
        return (val) => {
	        const {font_class = ''} = iconfont.glyphs.find(icon => {
		        return icon.unicode === val;
	        }) || {};
	        return `icon-${font_class}`;
        };
      },
    },
    watch: {
      'widget.tempRect': {
        handler() {
          this.updateChildrenRect();
        },
        immediate: true,
        deep: true
      },
      'widget.UI.data': {
        handler() {
          this.updateChildrenRect();
        },
        immediate: true,
        deep: true
      },
      'widget.UI.states': {
        handler(states = []) {
          this.widget.children.forEach(child => {
            child.UI.states.forEach((state, idx) => {
              const parentState = states[idx];
              if (!parentState) return;
              state.backStyle.backgroundColor = parentState.backStyle.backgroundColor;
            });
          });
        },
        immediate: true,
        deep: true
      },
    },
    mounted() {
      this.$EventBus.$on(`tabBarTabAdded-${this.widget.id}`, () => {
	      const newTabWidgetId = this.widget.addTab();
        this.tabChange(newTabWidgetId);
      });
      this.$EventBus.$on(`tabBarTabDeleted-${this.widget.id}`, (childId) => {
	      const newTabWidgetId = this.widget.deleteTab(childId);
	      newTabWidgetId && this.tabChange(newTabWidgetId);
      });
    },
    beforeDestroy() {
      this.$EventBus.$off(`tabBarTabAdded-${this.widget.id}`);
      this.$EventBus.$off(`tabBarTabDeleted-${this.widget.id}`);
    },
    methods: {
	    tabChange(widgetId) {
	      const activeWidget = WidgetFactory.getWidgetById(widgetId);
	      if (!activeWidget) return;
        if (!this.isSelectMode) {
          this.$EventBus.$emit('selectWidget', activeWidget);
        } else {
          this.$EventBus.$emit('selectWidgetForPicker', activeWidget);
        }
      },
      updateChildrenRect() {
        const {tabData = {}, tabSize = {}} = this.widget.UI.data;
        const {layout, offset = {}} = tabData;
        const {top = 0, bottom = 0} = offset;
        const {height: tabHeight = 0} = tabSize;
        let rect = {top: 0, left: 0, width: 600, height: 550};
        switch (layout) {
          case 'bottom':
            rect = {
              top: 0, left: 0,
              width: this.widget.tempRect.width,
              height: this.widget.tempRect.height - tabHeight - bottom
            }
            break;
          case 'top':
            rect = {
              top: tabHeight + top, left: 0,
              width: this.widget.tempRect.width,
              height: this.widget.tempRect.height - tabHeight - top
            }
            break;
          default:
            break;
        }
        this.widget.children.forEach(child => {
          child.draggable = true;
          child.resizable = true;
          child.rect = rect;
        });
        this.$nextTick(() => {
          this.widget.children.forEach(child => {
            child.draggable = false;
            child.resizable = false;
          });
        });
      }
    }
  };
</script>

<style lang="less" scoped>

  .tab-item-container {
    overflow: hidden;
  }

  .tab-container {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
  }

  .flex-item {
    flex-grow: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .tab-box {
    gap: 10px;
    cursor: pointer;
    height: 100%;
  }
</style>
